package org.graduation.rbac.controller;

import org.graduation.model.common.ResponseResult;
import org.graduation.model.dtos.RBAC.AssignAndRevokeRoleDTO;
import org.graduation.model.dtos.RBAC.CheckPermissionsDTO;
import org.graduation.model.dtos.RBAC.DesignateAndRevokeAdminDTO;
import org.graduation.model.dtos.RBAC.PermissionsInfoDTO;
import org.graduation.rbac.service.UserPermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/permission")
public class UserPermissionsController {
    @Autowired
    private UserPermissionService userPermissionService;

    /**
     * 任命项目管理员
     *
     * @param dto
     * @return
     */
    @RequestMapping(value = "/designate", method = RequestMethod.POST)
    public ResponseResult designateAdmin(@RequestBody DesignateAndRevokeAdminDTO dto) {
        return userPermissionService.designateAdmin(dto.getPId(), dto.getOwner(), dto.getUid());
    }

    /**
     * 撤销项目管理员
     *
     * @param dto
     * @return
     */
    @RequestMapping(value = "/revoke", method = RequestMethod.POST)
    public ResponseResult revokeAdmin(@RequestBody DesignateAndRevokeAdminDTO dto) {
        return userPermissionService.revokeAdmin(dto.getPId(), dto.getOwner(), dto.getUid());
    }

    /**
     * 获取用户关于某个项目所有权限信息
     *
     * @param dto
     * @return
     */
    @RequestMapping(value = "/permissions", method = RequestMethod.GET)
    public ResponseResult getAllPermissions(@RequestBody PermissionsInfoDTO dto) {
        return ResponseResult.success(userPermissionService.getUserAllPermissions(dto.getPId(), dto.getUid()));
    }

    /**
     * 检查某个用户是否具备某项权限
     *
     * @param dto
     * @return
     */
    @RequestMapping(value = "/check", method = RequestMethod.POST)
    public ResponseResult check(@RequestBody CheckPermissionsDTO dto) {
        return userPermissionService.checkPermission(dto.getPId(), dto.getUid(), dto.getPermissions());
    }

    /**
     * 分配新角色
     *
     * @param dto
     * @return
     */
    @RequestMapping(value = "/assign_role", method = RequestMethod.POST)
    public ResponseResult assignRole(@RequestBody AssignAndRevokeRoleDTO dto) {
        return userPermissionService.assignRole(dto.getPId(), dto.getUid(), dto.getRoles());
    }

    /**
     * 撤销角色
     *
     * @param dto
     * @return
     */
    @RequestMapping(value = "revoke_role", method = RequestMethod.POST)
    public ResponseResult revokeRoles(@RequestBody AssignAndRevokeRoleDTO dto) {
        return userPermissionService.revokeRoles(dto.getPId(), dto.getUid(), dto.getRoles());
    }
}